﻿namespace EyeOpen.Web.Mvc
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Linq.Expressions;
	using System.Web.Mvc;
	using System.Web.Routing;

	public static class HtmlHelperExtensions
	{
		public static MvcHtmlString FieldNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
		{
			return LabelFor(html, expression, new { @class = "field" });
		}

		public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
		{
			return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
		}

		public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
		{
			var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
			var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
			
			var labelText = 
				metadata.DisplayName ?? 
					metadata.PropertyName ?? htmlFieldName.Split('.').Last();
			
			if (string.IsNullOrEmpty(labelText))
			{
				return MvcHtmlString.Empty;
			}

			var tag = new TagBuilder("label");
			tag.MergeAttributes(htmlAttributes);
			tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
			tag.SetInnerText(labelText);

			return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
		}
	}
}